// socket功能
import SockJS from "sockjs-client";
import Stomp from "stompjs";
const wsUrl = "http://172.14.100.1:8091/message/center"
let stompClient = null;

// 连接ws
export function connectionSocket(userId, tenantId, store) {
  let socket = new SockJS(`${wsUrl}?userId=${userId}&tenantId=${tenantId}`);
  stompClient = Stomp.over(socket);
  // 向服务器发起websocket连接
  stompClient.connect({
      Authorization: "", // 定义客户端的认证信息,按需求配置
    },
    (resp) => {
      console.log('connect response', resp);
      stompClient.send("/app/init/query", {}, JSON.stringify({
        userId,
        tenantId
      }));
      stompClient.subscribe('/user/queue/init/query', function (response) {
        let data = JSON.parse(response.body);
        console.log("INIT_DATA", data);
        store.commit("INIT_DATA", data);
      });

      // 接收服务端主动推送消息
      stompClient.subscribe('/user/queue/getMessage', function (response) {
        let data = JSON.parse(response.body);
        console.log("SEND_MESSAGE", data);
        store.commit("SEND_MESSAGE", data);
      });

      // 接收已读消息
      // stompClient.subscribe('/user/queue/receive/readed', function (response) {
      //   var message = JSON.parse(response.body);
      //   alert(message);
      // });
      // 更新消息
      // stompClient.subscribe('/user/queue/refresh/message', function (response) {
      //   var message = JSON.parse(response.body);
      //   alert(message);
      // });

      // stompClient.send("/app/init/query", {}, '654366374251302912');
      // var param1 = {
      //   "source": "YZFJTSW",
      //   "msgIds": ["88888"],
      //   "userId": "654366374251302912"
      // };
      // stompClient.send("/app/receive/readed", {}, JSON.stringify(param1));
      // var param2 = {
      //   "source": "YZFJTSW",
      //   "userId": "654366374251302912"
      // };
      // stompClient.send("/app/refresh/message", {}, JSON.stringify(param2));
    },
    (err) => {
      // 连接发生错误时的处理函数
      console.log("失败");
      console.log(err);
    }
  );
}

export function getStomp() {
  return stompClient;
};